<template>
  <div class="storage-fee-list">
    <el-card class="list-card">
      <template #header>
        <div class="card-header">
          <span>仓储费用管理</span>
          <div>
            <el-button type="primary" @click="handleAdd">新增费用</el-button>
          </div>
        </div>
      </template>
      
      <el-table
        :data="storageFees"
        style="width: 100%"
        v-loading="loading"
      >
        <el-table-column label="序号" width="80">
          <template #default="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column label="仓储记录ID" prop="recordId" width="100" />
        <el-table-column label="货物ID" prop="cargoId" width="80" />
        <el-table-column label="费用金额" prop="feeAmount" />
        <el-table-column label="计费日期">
          <template #default="scope">
            {{ formatDate(scope.row.calculationDate) }}
          </template>
        </el-table-column>
        <el-table-column label="支付状态">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.paymentStatus)">
              {{ scope.row.displayStatus || getStatusText(scope.row.paymentStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="240">
          <template #default="scope">
            <el-button type="primary" link @click="handleDetail(scope.row)">详情</el-button>
            <el-button 
              type="success" 
              link 
              v-if="scope.row.paymentStatus === '未支付'"
              @click="handlePay(scope.row)"
            >支付</el-button>
            <el-button 
              type="danger" 
              link 
              @click="handleDelete(scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    
    <!-- 新增费用表单弹窗 -->
    <el-dialog
      v-model="addDialogVisible"
      title="新增仓储费用"
      width="500px"
    >
      <el-form 
        :model="feeForm" 
        label-width="120px"
        :rules="formRules"
        ref="feeFormRef"
      >
        <el-form-item label="仓储记录" prop="recordId">
          <el-select v-model="feeForm.recordId" placeholder="请选择仓储记录" style="width: 100%" @change="fetchRecordDetails">
            <el-option 
              v-for="record in storageRecords" 
              :key="record.recordId" 
              :label="`记录ID: ${record.recordId} - 货物ID: ${record.cargoId}`"
              :value="record.recordId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="货物ID">
          <el-input v-model="feeForm.cargoId" disabled />
        </el-form-item>
        <el-form-item label="计费日期" prop="calculationDate">
          <el-date-picker 
            v-model="feeForm.calculationDate" 
            type="date" 
            placeholder="选择日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="计费天数" prop="daysCounted">
          <el-input-number v-model="feeForm.daysCounted" :min="1" style="width: 100%" />
        </el-form-item>
        <el-form-item label="费用规则" prop="ruleId">
          <el-select v-model="feeForm.ruleId" placeholder="请选择费用规则" style="width: 100%" @change="applyFeeRule">
            <el-option 
              v-for="rule in feeRules" 
              :key="rule.ruleId" 
              :label="`规则ID: ${rule.ruleId} - ${rule.ruleName}`" 
              :value="rule.ruleId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="日费率" prop="dailyRate">
          <el-input-number v-model="feeForm.dailyRate" :step="0.01" :precision="2" style="width: 100%" />
        </el-form-item>
        <el-form-item label="费用金额" prop="feeAmount">
          <el-input-number 
            v-model="feeForm.feeAmount" 
            :step="0.01" 
            :precision="2" 
            style="width: 100%"
            :disabled="autoCalculateAmount"
          />
        </el-form-item>
        <el-form-item label="自动计算金额">
          <el-switch v-model="autoCalculateAmount" @change="calculateAmount" />
        </el-form-item>
        <el-form-item label="支付状态" prop="paymentStatus">
          <el-select v-model="feeForm.paymentStatus" placeholder="请选择支付状态" style="width: 100%">
            <el-option label="未支付" value="未支付" />
            <el-option label="已支付" value="已支付" />
            <el-option label="处理中" value="处理中" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitFeeForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 查看详情弹窗 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="费用详情"
      width="500px"
    >
      <div class="fee-detail" v-if="currentFee">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="费用ID">{{ currentFee.feeId }}</el-descriptions-item>
          <el-descriptions-item label="仓储记录ID">{{ currentFee.recordId }}</el-descriptions-item>
          <el-descriptions-item label="货物ID">{{ currentFee.cargoId }}</el-descriptions-item>
          <el-descriptions-item label="计费日期">{{ formatDate(currentFee.calculationDate) }}</el-descriptions-item>
          <el-descriptions-item label="计费天数">{{ currentFee.daysCounted }}</el-descriptions-item>
          <el-descriptions-item label="日费率">{{ currentFee.dailyRate }}</el-descriptions-item>
          <el-descriptions-item label="费用金额">{{ currentFee.feeAmount }}</el-descriptions-item>
          <el-descriptions-item label="规则ID">{{ currentFee.ruleId }}</el-descriptions-item>
          <el-descriptions-item label="支付状态">
            <el-tag :type="getStatusType(currentFee.paymentStatus)">
              {{ currentFee.displayStatus || getStatusText(currentFee.paymentStatus) }}
            </el-tag>
          </el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { ref, onMounted, watch, reactive } from 'vue'
import { useStore } from 'vuex'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'

export default {
  name: 'StorageFeeList',
  setup() {
    const store = useStore()
    const storageFees = ref([])
    const loading = ref(false)
    const storageRecords = ref([])
    const feeRules = ref([])
    
    // 弹窗控制
    const addDialogVisible = ref(false)
    const detailDialogVisible = ref(false)
    
    // 表单相关
    const feeFormRef = ref(null)
    const feeForm = reactive({
      recordId: '',
      cargoId: '',
      calculationDate: '',
      daysCounted: 1,
      dailyRate: 0,
      feeAmount: 0,
      ruleId: '',
      paymentStatus: '未支付'
    })
    
    const autoCalculateAmount = ref(true)
    
    const currentFee = ref(null)
    
    // 表单校验规则
    const formRules = {
      recordId: [{ required: true, message: '请选择仓储记录', trigger: 'change' }],
      calculationDate: [{ required: true, message: '请选择计费日期', trigger: 'change' }],
      daysCounted: [{ required: true, message: '请输入计费天数', trigger: 'blur' }],
      dailyRate: [{ required: true, message: '请输入日费率', trigger: 'blur' }],
      feeAmount: [{ required: true, message: '请输入费用金额', trigger: 'blur' }],
      ruleId: [{ required: true, message: '请选择费用规则', trigger: 'change' }],
      paymentStatus: [{ required: true, message: '请选择支付状态', trigger: 'change' }]
    }
    
    // 监听计算金额
    watch([() => feeForm.daysCounted, () => feeForm.dailyRate], () => {
      if (autoCalculateAmount.value) {
        calculateAmount()
      }
    })
    
    const calculateAmount = () => {
      if (autoCalculateAmount.value && feeForm.daysCounted && feeForm.dailyRate) {
        feeForm.feeAmount = feeForm.daysCounted * feeForm.dailyRate
      }
    }
    
    // 应用费用规则，自动设置日费率
    const applyFeeRule = (ruleId) => {
      if (!ruleId) return
      
      const selectedRule = feeRules.value.find(rule => rule.ruleId === ruleId)
      if (selectedRule && selectedRule.dailyRate) {
        feeForm.dailyRate = selectedRule.dailyRate
        
        // 如果启用自动计算，则重新计算总金额
        if (autoCalculateAmount.value) {
          calculateAmount()
        }
      }
    }
    
    // 根据仓储记录获取详情并自动填充
    const fetchRecordDetails = async (recordId) => {
      if (!recordId) return
      
      try {
        const response = await axios.get(`storage-records/${recordId}`)
        if (response.data.code === 200) {
          const record = response.data.data
          
          // 更新货物ID
          feeForm.cargoId = record.cargoId
          
          // 设置计费日期为当前日期
          feeForm.calculationDate = formatDateToYYYYMMDD(new Date())
          
          // 计算存储天数
          const entryTime = new Date(record.entryTime)
          let exitTime
          
          // 如果有实际出库时间，使用实际出库时间，否则使用预期出库时间或当前日期
          if (record.actualExitTime) {
            exitTime = new Date(record.actualExitTime)
          } else if (record.expectedExitTime) {
            exitTime = new Date(record.expectedExitTime)
            
            // 如果预期出库时间在未来，使用当前日期
            const today = new Date()
            if (exitTime > today) {
              exitTime = today
            }
          } else {
            exitTime = new Date() // 默认使用当前日期
          }
          
          // 计算天数（向上取整）
          const daysDiff = Math.ceil((exitTime - entryTime) / (1000 * 60 * 60 * 24))
          feeForm.daysCounted = daysDiff > 0 ? daysDiff : 1
          
          // 查找适用的费用规则
          if (record.cargoId) {
            try {
              // 获取货物信息
              const cargoResponse = await axios.get(`cargos/${record.cargoId}`)
              if (cargoResponse.data.code === 200) {
                const cargo = cargoResponse.data.data
                
                // 根据货物类型和所在区域查找匹配的规则
                if (feeRules.value.length === 0) {
                  await fetchFeeRules()
                }
                
                console.log('所有费用规则:', feeRules.value)
                console.log('当前货物:', cargo)
                
                // 优先匹配货物类型和区域完全匹配的规则
                let matchedRule = feeRules.value.find(rule => 
                  rule.cargoType === cargo.cargoType && 
                  rule.areaId === cargo.entryAreaId && 
                  rule.isActive === true
                )
                
                // 如果没有找到完全匹配的，尝试只匹配货物类型
                if (!matchedRule) {
                  matchedRule = feeRules.value.find(rule => 
                    rule.cargoType === cargo.cargoType && 
                    rule.isActive === true
                  )
                }
                
                // 如果仍然没有找到，尝试只匹配区域
                if (!matchedRule) {
                  matchedRule = feeRules.value.find(rule => 
                    rule.areaId === cargo.entryAreaId && 
                    rule.isActive === true
                  )
                }
                
                console.log('匹配到的规则:', matchedRule)
                
                if (matchedRule) {
                  feeForm.ruleId = matchedRule.ruleId
                  feeForm.dailyRate = matchedRule.dailyRate
                }
              }
            } catch (error) {
              console.error('获取货物信息失败:', error)
            }
          }
          
          // 重新计算金额
          calculateAmount()
        }
      } catch (error) {
        console.error('获取仓储记录详情失败:', error)
        ElMessage.error('获取仓储记录详情失败')
      }
    }
    
    const formatDateToYYYYMMDD = (date) => {
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      return `${year}-${month}-${day}`
    }
    
    const fetchStorageFees = async () => {
      loading.value = true
      try {
        const fees = await store.dispatch('fetchStorageFees')
        console.log('获取到的仓储费用数据:', fees)
        storageFees.value = fees
      } catch (error) {
        console.error('获取仓储费用失败:', error)
        ElMessage.error('获取仓储费用失败')
      } finally {
        loading.value = false
      }
    }
    
    const fetchStorageRecords = async () => {
      try {
        const records = await store.dispatch('fetchStorageRecords')
        storageRecords.value = records
      } catch (error) {
        console.error('获取仓储记录失败:', error)
        ElMessage.error('获取仓储记录失败')
      }
    }
    
    const fetchFeeRules = async () => {
      try {
        const rules = await store.dispatch('fetchFeeRules')
        feeRules.value = rules
      } catch (error) {
        console.error('获取费用规则失败:', error)
        ElMessage.error('获取费用规则失败')
      }
    }
    
    const resetForm = () => {
      if (feeFormRef.value) {
        feeFormRef.value.resetFields()
      }
      Object.assign(feeForm, {
        recordId: '',
        cargoId: '',
        calculationDate: '',
        daysCounted: 1,
        dailyRate: 0,
        feeAmount: 0,
        ruleId: '',
        paymentStatus: '未支付'
      })
    }
    
    const formatDate = (dateString) => {
      if (!dateString) return ''
      const date = new Date(dateString)
      return date.toLocaleDateString('zh-CN', { 
        year: 'numeric', 
        month: '2-digit', 
        day: '2-digit'
      })
    }
    
    const getStatusType = (status) => {
      switch(status) {
        case '已支付':
        case '已开票':
          return 'success'
        case '未支付':
          return 'danger'
        case '处理中':
          return 'warning'
        default:
          return 'info'
      }
    }
    
    const getStatusText = (status) => {
      if (!status) return '未知'
      if (status === '已开票') return '已支付'
      return status
    }
    
    const handleAdd = () => {
      resetForm()
      addDialogVisible.value = true
      if (storageRecords.value.length === 0) {
        fetchStorageRecords()
      }
      if (feeRules.value.length === 0) {
        fetchFeeRules()
      }
    }
    
    const submitFeeForm = async () => {
      if (!feeFormRef.value) return
      
      await feeFormRef.value.validate(async (valid) => {
        if (valid) {
          try {
            const response = await axios.post('storage-fees', feeForm)
            if (response.data.code === 200) {
              ElMessage.success('新增费用成功')
              addDialogVisible.value = false
              fetchStorageFees()
            } else {
              ElMessage.error(response.data.message || '新增费用失败')
            }
          } catch (error) {
            console.error('新增费用失败:', error)
            ElMessage.error('新增费用失败: ' + error.message)
          }
        } else {
          ElMessage.warning('请填写完整的表单信息')
          return false
        }
      })
    }
    
    const handleDetail = async (fee) => {
      try {
        // 获取最新的费用详情数据
        const response = await axios.get(`storage-fees/${fee.feeId}`)
        if (response.data.code === 200) {
          const feeData = response.data.data;
          // 如果状态是"已开票"，添加displayStatus为"已支付"
          if (feeData.paymentStatus === '已开票') {
            feeData.displayStatus = '已支付';
          } else {
            feeData.displayStatus = feeData.paymentStatus;
          }
          currentFee.value = feeData;
          detailDialogVisible.value = true
        } else {
          ElMessage.error(response.data.message || '获取费用详情失败')
        }
      } catch (error) {
        console.error('获取费用详情失败:', error)
        ElMessage.error('获取费用详情失败')
      }
    }
    
    const handlePay = (fee) => {
      ElMessageBox.confirm(
        `确认支付金额: ${fee.feeAmount}元?`,
        '支付确认',
        {
          confirmButtonText: '确认支付',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).then(async () => {
        try {
          const response = await axios.put(`storage-fees/${fee.feeId}/pay`)
          if (response.data.code === 200) {
            ElMessage.success('支付成功')
            fetchStorageFees()
          } else {
            ElMessage.error(response.data.message || '支付失败')
          }
        } catch (error) {
          console.error('支付费用失败:', error)
          ElMessage.error('支付费用失败')
        }
      }).catch(() => {
        ElMessage.info('已取消支付')
      })
    }
    
    const handleDelete = (fee) => {
      ElMessageBox.confirm(
        `确认删除费用记录: ID ${fee.feeId}，金额 ${fee.feeAmount}元?`,
        '删除确认',
        {
          confirmButtonText: '确认删除',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).then(async () => {
        try {
          const response = await axios.delete(`storage-fees/${fee.feeId}`)
          if (response.data.code === 200) {
            ElMessage.success('删除成功')
            fetchStorageFees()
          } else {
            ElMessage.error(response.data.message || '删除失败')
          }
        } catch (error) {
          console.error('删除费用失败:', error)
          ElMessage.error('删除费用失败: ' + error.message)
        }
      }).catch(() => {
        ElMessage.info('已取消删除')
      })
    }
    
    onMounted(() => {
      fetchStorageFees()
      
      // 检查是否需要打开详情弹窗
      const viewFeeId = localStorage.getItem('viewFeeDetail')
      console.log('StorageFeeList mounted, viewFeeId from localStorage:', viewFeeId)
      
      if (viewFeeId) {
        // 清除localStorage中的标记
        localStorage.removeItem('viewFeeDetail')
        console.log('准备展示费用详情，ID:', viewFeeId)
        
        // 获取费用详情并打开弹窗
        setTimeout(() => {
          console.log('执行handleDetail，ID:', viewFeeId)
          // 先检查数据是否已加载
          if (storageFees.value.length === 0) {
            console.log('费用数据未加载，再次获取数据')
            fetchStorageFees().then(() => {
              console.log('数据加载完成，现在展示详情')
              handleDetail({ feeId: viewFeeId })
            })
          } else {
            handleDetail({ feeId: viewFeeId })
          }
        }, 500) // 等待数据加载完成
      }
    })
    
    return {
      storageFees,
      loading,
      storageRecords,
      feeRules,
      addDialogVisible,
      detailDialogVisible,
      feeForm,
      feeFormRef,
      formRules,
      autoCalculateAmount,
      currentFee,
      handleAdd,
      handleDetail,
      handlePay,
      handleDelete,
      formatDate,
      getStatusType,
      getStatusText,
      submitFeeForm,
      calculateAmount,
      fetchRecordDetails,
      formatDateToYYYYMMDD,
      applyFeeRule
    }
  }
}
</script>

<style scoped>
.storage-fee-list {
  padding: 20px;
}

.list-card {
  width: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.fee-detail {
  padding: 10px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style>
